import TabMenu from './data';

Component({
  data: {
    active: 0,
    list: TabMenu,
  },

  methods: {
    onChange(event) {
      const index = event.currentTarget.dataset.index;
      this.setData({ active: index });
      const targetUrl = this.data.list[index].url.startsWith('/')
        ? this.data.list[index].url
        : `/${this.data.list[index].url}`;
      wx.switchTab({ url: targetUrl });
    },

    init() {
      const pages = getCurrentPages();
      
      if (!pages.length) {
        console.warn('Page stack is empty. Cannot initialize active tab.');
        return;
      }
    
      const page = pages.pop();
      const route = page ? page.route.split('?')[0] : '';
      const active = this.data.list.findIndex(
        (item) =>
          (item.url.startsWith('/') ? item.url.substr(1) : item.url) === route
      );
    
      if (active !== -1) {
        this.setData({ active });
      } else {
        console.warn('Route not found in tab list:', route);
      }
    },
  },

  lifetimes: {
    attached() {
      this.init();
    },
  },
});